<?php

namespace App\Admin\Actions\Grid\Customer;

use App\Enums\ReceptionType;
use App\Models\Customer;
use Dcat\Admin\Actions\Response;
use Dcat\Admin\Grid\RowAction;
use Illuminate\Http\Request;

class Delete extends RowAction
{
    /**
     * @return string
     */
    protected $title = '删除';
    protected int $type;

    public function __construct(int $type = ReceptionType::SALE)
    {
        $this->type = $type;
        parent::__construct($this->title);
    }

    /**
     * Handle the action request.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function handle(Request $request): Response
    {
        $customer = Customer::query()->where('id', $this->getKey())->first();
        if ($request->get('type') == ReceptionType::RECEPTION && $customer->sale_user_id) {
            return $this->response()->error('已分配至销售部，不可删除');
        }
        if ($request->get('type') == ReceptionType::SALE) {
            if (\App\Models\SalePerformance::query()->where('customer_id', $customer->id)->exists()) {
                return $this->response()->error('存在销售业绩，不可删除');
            }
            if ($customer->return_user_id) {
                return $this->response()->error('已分配至复诊部，不可删除');
            }
            $customer->delete();
        }
        if ($request->get('type') == ReceptionType::RETURN_VISIT) {
            //存在业绩不能删除
            if (\App\Models\ReturnPerformance::query()->where('customer_id', $customer->id)->exists()) {
                return $this->response()->error('存在销售业绩，不可删除');
            }
            $customer->return_user_id = 0;
            $customer->return_time = null;
            $customer->return_remark = '';
            $customer->save();
        }
        return $this->response()
            ->success(trans('admin.processed_successfully'))
            ->refresh();
    }

    /**
     * @return string
     */
    public function confirm(): string
    {
        return '确定删除吗？';
    }

    public function html(): string
    {
        $this->defaultHtmlAttribute('href', 'javascript:void(0)');

        return <<<HTML
<a {$this->formatHtmlAttributes()}><i class="feather icon-trash-2"> {$this->title()}</i></a>
HTML;
    }

    public function parameters(): array
    {
        return [
            'type' => $this->type
        ];
    }
}
